﻿using DongFangGuoKai.WMS.IApiService;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using Quartz;

namespace DongFangGuoKai.WMSPlatform.WebApi.Jobs.JobDetails
{
    [DisallowConcurrentExecution]
    public class EmptyContanierToScrennAreaJob : IJob
    {
        public EmptyContanierToScrennAreaJob(WMSPlatformContext context, ILogger<EmptyContanierToScrennAreaJob> logger, IAGVService aGVApiService)
        {
            Context = context;
            Logger = logger;
            AGVApiService = aGVApiService;
        }
        public WMSPlatformContext Context { get; }
        public ILogger<EmptyContanierToScrennAreaJob> Logger { get; }
        public IAGVService AGVApiService { get; }


        public Task Execute(IJobExecutionContext context)
        {
            var emptyCellList = Context.TCells.Where(t => t.Status == 1 && t.BusinessType == 0 && t.IsLock == false && t.FullStatus == 0 && t.LogicalPartCode == "DistributionArea")
                .OrderBy(o => o.LineNo)
                .OrderBy(o => o.LayerNo)
                .OrderBy(o => o.ColumnNo)
                .Take(5).ToList();

            Logger.LogWarning("0 */1  5-16 ? * MON-FR");
            if (emptyCellList != null && emptyCellList.Count > 0)
            {
                foreach (var emptyToCell in emptyCellList)
                {
                    var pallet = Context.TPallets.FirstOrDefault(t => t.PalletBarcode == emptyToCell.LogicalPartCode);
                    if (pallet != null)
                    {
                        Logger.LogError($"分拨仓位：{emptyToCell.Name}分配托盘：{pallet.PalletName}");
                        return Task.CompletedTask;
                    }

                    var fromCell = Context.TCells.Where(t => t.IsLock == false && t.LogicalPartCode != "DistributionArea" && t.BusinessType == 0 && t.FullStatus == 0 && t.Status == 1).FirstOrDefault();
                    if (fromCell == null)
                    {
                        Logger.LogError($"空托盘仓位不存在！");
                        return Task.CompletedTask;
                    }
                    var fromCellPallet = Context.TPallets.FirstOrDefault(t => t.LocationCode == fromCell.Code);
                    if (fromCellPallet == null)
                    {
                        Logger.LogError($"仓位找不到空托盘信息！");
                        return Task.CompletedTask;
                    }

                    using (var tran = Context.Database.BeginTransaction())
                    {
                        //修改托盘位置信息
                        fromCellPallet.LocationCode = fromCell.Code;
                        fromCellPallet.ErplocationName = fromCell.Erpcode;
                        fromCellPallet.WarehouseName = fromCell.WhName;
                        fromCellPallet.WarehouseId = fromCell.WhId;
                        fromCellPallet.WarehouseCode = fromCell.WhCode;
                        Context.TPallets.Update(fromCellPallet);
                        Context.SaveChanges();

                        //目标储位
                        emptyToCell.Status = 2;//锁定仓位  
                        emptyToCell.BusinessType = EmBusinessType.Move; //移位
                        emptyToCell.IsLock = true; //锁定
                        Context.TCells.Update(emptyToCell);
                        Context.SaveChanges();

                        //源储位
                        fromCell.Status = 2;
                        fromCell.BusinessType = EmBusinessType.Move; //移位
                        fromCell.IsLock = true; //锁定
                        Context.TCells.Update(fromCell);
                        Context.SaveChanges();

                        Guid guid = Guid.NewGuid();
                        TInstruct instruct = new TInstruct()
                        {
                            BusinessGroupId = guid,
                            CreateUserId = 1,
                            CreateUserName = "admin",
                            Status = 2,
                            Action = EmDeviceAction.Transport,
                            WorkDeviceType = EmWorkDeviceType.AGV,
                            InstructType = EmInstructType.Move,
                            ExpectedToLocation = emptyToCell.Code,//目标地址
                            FromLocation = fromCell.Code,   //源地址
                            InstructIndex = 1,
                            PalletBarcode = fromCellPallet.PalletBarcode,
                            ScanedBarcode = fromCellPallet.PalletBarcode,
                            Priority = 9999,
                            FinishedQty = 0,
                            LogicalCellAddr = emptyToCell.Erpcode,
                            StartTime = DateTime.Now,
                        };
                        Context.TInstructs.Add(instruct);
                        Context.SaveChanges();

                        string ctnrType = "";
                        string taskType = "";
                        if (fromCellPallet.Type == 1)
                        {
                            ctnrType = "2";
                            taskType = "A11";
                        }
                        else if (fromCellPallet.Type == 2)
                        {
                            ctnrType = "1";
                            taskType = "A10";
                        }
                        //添加任务单
                        AddTaskModel taskModel = new AddTaskModel();

                        //生成32位uuid
                        taskModel.reqCode = guid.ToString("N");
                        taskModel.clientCode = "PDA";
                        //大料箱任务类型
                        taskModel.TaskTyp = taskType;


                        taskModel.CtnrTyp = ctnrType;
                        //生成36位uuid
                        taskModel.taskCode = guid.ToString();

                        //任务起始点仓位编码
                        taskModel.PositionCodePath = new PositionCodePathDto[2] {
                    new PositionCodePathDto() {
                        PositionCode=fromCell.Erpcode,// 起始地址 D00080A2502013
                        Type="05"
                    },
                    new PositionCodePathDto() {
                        PositionCode=emptyToCell.Erpcode,//ERP目标地址
                        Type="05"
                    }
                };
                        var res = AGVApiService.CreateTask(taskModel);
                        if (res.code == "1")
                        {
                            tran.Rollback();
                            Logger.LogError("AGV调用失败：" + res.message);
                            return Task.CompletedTask;
                        }
                        Logger.LogInformation("成功！！！");
                        tran.Commit();

                    }

                }
            }


            Console.WriteLine(DateTime.Now);
            Console.WriteLine("--------------------------");

            return Task.CompletedTask;
        }
    }
}
